package com.lyy.project.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lyy.common.utils.*;
import com.lyy.common.utils.excel.ExcelUtils;
import com.lyy.common.utils.jxls.JxlsExport;
import com.lyy.project.pojo.ProProjectGlobal;
import com.lyy.project.service.ProProjectGlobalService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 项目全局设置(ProProjectGlobal)表控制层
 *
 * @author Yw
 * @since 2021-02-01 17:22:33
 */
@RestController
@RequestMapping("/proProjectGlobal")
public class ProProjectGlobalController {
    /**
     * 服务对象
     */
    @Resource
    private ProProjectGlobalService proProjectGlobalService;

    /**
     * 创建项目全局设置
     * /proProjectGlobal/createProProjectGlobal
     * { "environment":"环境",  "http":"项目全局请求参数",  "projectId":"",  "status":"项目全局状态" }
     *
     * @param environment 环境
     * @param http        项目全局请求参数
     * @param projectId
     * @param status      项目全局状态
     * @return
     */
    @PostMapping("/createProProjectGlobal")
    public Map<String, Object> createProProjectGlobal(ProProjectGlobal proProjectGlobal) {
        AssertUtils.notNull(proProjectGlobal.getEnvironment(), "环境不能为空");
        AssertUtils.notNull(proProjectGlobal.getHttp(), "项目全局请求参数不能为空");
        AssertUtils.notNull(proProjectGlobal.getProjectId(), "不能为空");
        AssertUtils.notNull(proProjectGlobal.getStatus(), "项目全局状态不能为空");
        proProjectGlobalService.createProProjectGlobal(proProjectGlobal);
        return ResultUtils.getResult(ResultInfo.SUCCESS);
    }

    /**
     * 根据主键修改项目全局设置
     * /proProjectGlobal/updateProProjectGlobal
     * { "id":"",  "environment":"环境",  "http":"项目全局请求参数",  "projectId":"",  "status":"项目全局状态" }
     *
     * @param id
     * @param environment 环境
     * @param http        项目全局请求参数
     * @param projectId
     * @param status      项目全局状态
     * @return
     */
    @PutMapping("/updateProProjectGlobal")
    public Map<String, Object> updateProProjectGlobal(ProProjectGlobal proProjectGlobal) {
        AssertUtils.notNull(proProjectGlobal.getId(), "不能为空");
        AssertUtils.notNull(proProjectGlobal.getEnvironment(), "环境不能为空");
        AssertUtils.notNull(proProjectGlobal.getHttp(), "项目全局请求参数不能为空");
        AssertUtils.notNull(proProjectGlobal.getProjectId(), "不能为空");
        AssertUtils.notNull(proProjectGlobal.getStatus(), "项目全局状态不能为空");
        proProjectGlobalService.updateProProjectGlobal(proProjectGlobal);
        return ResultUtils.getResult(ResultInfo.SUCCESS);
    }

    /**
     * 根据主键获取单个项目全局设置
     * /proProjectGlobal/getProProjectGlobal
     * { "id":"" }
     *
     * @param id
     * @return
     */
    @GetMapping("/getProProjectGlobal")
    public Map<String, Object> getProProjectGlobal(ProProjectGlobal proProjectGlobal) {
        AssertUtils.notNull(proProjectGlobal.getId(), "不能为空");
        ProProjectGlobal entity = proProjectGlobalService.getProProjectGlobal(proProjectGlobal);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("proProjectGlobal", entity);
        return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
    }


    /**
     * 根据主键删除项目全局设置
     * /proProjectGlobal/deleteProProjectGlobal
     * { "id":"" }
     *
     * @param id
     * @return
     */
    @DeleteMapping("/deleteProProjectGlobal")
    public Map<String, Object> deleteProProjectGlobal(ProProjectGlobal proProjectGlobal) {
        AssertUtils.notNull(proProjectGlobal.getId(), "不能为空");
        proProjectGlobalService.deleteProProjectGlobal(proProjectGlobal);
        return ResultUtils.getResult(ResultInfo.SUCCESS);
    }

    /**
     * 查询项目全局设置列表
     * /proProjectGlobal/selectProProjectGlobalList
     * { "id":"",  "environment":"环境",  "http":"项目全局请求参数",  "projectId":"",  "status":"项目全局状态" }
     *
     * @param id
     * @param environment 环境
     * @param http        项目全局请求参数
     * @param projectId
     * @param status      项目全局状态
     * @return
     */
    @GetMapping("/selectProProjectGlobalList")
    public Map<String, Object> selectProProjectGlobalList(ProProjectGlobal proProjectGlobal) {
        List<ProProjectGlobal> proProjectGlobals = proProjectGlobalService.selectProProjectGlobalList(proProjectGlobal);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("proProjectGlobals", proProjectGlobals);
        return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
    }

    /**
     * 查询项目全局设置列表
     * /proProjectGlobal/selectProProjectGlobalCount
     * { "id":"", "environment":"环境", "http":"项目全局请求参数", "projectId":"", "status":"项目全局状态"}
     *
     * @param id
     * @param environment 环境
     * @param http        项目全局请求参数
     * @param projectId
     * @param status      项目全局状态
     * @return
     */
    @GetMapping("/selectProProjectGlobalCount")
    public Map<String, Object> selectProProjectGlobalCount(ProProjectGlobal proProjectGlobal) {
        int count = proProjectGlobalService.selectProProjectGlobalCount(proProjectGlobal);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("count", count);
        return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
    }


    /**
     * 查询项目全局设置列表分页
     * /proProjectGlobal/selectProProjectGlobalPage
     * { "id":"",  "environment":"环境",  "http":"项目全局请求参数",  "projectId":"",  "status":"项目全局状态" ,"pageNum":"页码","pageSize":"条数"}
     *
     * @param pageNum     页码
     * @param pageSize    页数
     * @param id
     * @param environment 环境
     * @param http        项目全局请求参数
     * @param projectId
     * @param status      项目全局状态
     * @return
     */
    @GetMapping("/selectProProjectGlobalPage")
    public Map<String, Object> selectProProjectGlobalPage(ProProjectGlobal proProjectGlobal, Integer pageNum, Integer pageSize) {
        AssertUtils.notNull(pageNum, "页码不能为空!");
        AssertUtils.notNull(pageSize, "条数不能为空!");
        PageHelper.startPage(pageNum, pageSize);
        List<ProProjectGlobal> proProjectGlobals = proProjectGlobalService.selectProProjectGlobalList(proProjectGlobal);
        PageInfo<ProProjectGlobal> pageInfo = new PageInfo<>(proProjectGlobals);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageInfo", pageInfo);
        return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
    }


    /**
     * 导出项目全局设置
     * /proProjectGlobal/exportProProjectGlobalExcel
     * { "id":"",  "environment":"环境",  "http":"项目全局请求参数",  "projectId":"",  "status":"项目全局状态" }
     *
     * @param id
     * @param environment 环境
     * @param http        项目全局请求参数
     * @param projectId
     * @param status      项目全局状态
     * @return
     */
    @GetMapping("/exportProProjectGlobalExcel")
    public void exportProProjectGlobalExcel(HttpServletRequest request, HttpServletResponse response, ProProjectGlobal proProjectGlobal) {
        List<ProProjectGlobal> proProjectGlobals = proProjectGlobalService.selectProProjectGlobalList(proProjectGlobal);
        if (CommonUtils.isNotEmpty(proProjectGlobals)) {
            List<String> titles = new ArrayList<>();
            titles.add(" 序号 ");
            titles.add(" 环境 ");
            titles.add(" 项目全局请求参数 ");
            titles.add("    ");
            titles.add(" 项目全局状态 ");
            List<List<String>> values = new ArrayList<>();
            int k = 0;
            for (ProProjectGlobal entity : proProjectGlobals) {
                List<String> value = new ArrayList<>();
                value.add((++k) + "");
                value.add(entity.getEnvironment() + "");
                value.add(entity.getHttp() + "");
                value.add(entity.getProjectId());
                value.add(entity.getStatus() + "");
                values.add(value);
            }
            String address = Constants.address + "/wisdom/template/customTemplate.xls";
            String excelName = "项目全局设置.xls";
            Map<String, Object> beans = new HashMap<>();
            beans.put("titles", titles);
            beans.put("values", values);
            beans.put("date", DateUtils.formatDateTime(new Date()));
            JxlsExport.export(request, response, beans, excelName, address);
        }
    }


    /**
     * /proProjectGlobal/importProProjectGlobalExcel  从excel表导入项目全局设置
     * 导入excel文件
     * {"file":"excel文件"}
     *
     * @param file excel文件
     */
    @PostMapping("/importProProjectGlobalExcel")
    public Map<String, Object> importProProjectGlobalExcel(MultipartFile file) {
        if (file.isEmpty()) {
            return ResultUtils.getResult(ResultInfo.UPLOAD_NOT_EXISTS);
        }
        // 文件名称
        String fileName = file.getOriginalFilename();
        if (StringUtils.isBlank(fileName)) {
            return ResultUtils.getResult(ResultInfo.UPLOAD_NOT_EXISTS);
        }
        try {
            InputStream inputStream = file.getInputStream();
            //创建工作簿
            Workbook wb = null;
            //判断表格格式
            if (fileName.toLowerCase().endsWith("xls")) {
                wb = new HSSFWorkbook(inputStream);
            } else if (fileName.toLowerCase().endsWith("xlsx")) {
                wb = new XSSFWorkbook(inputStream);
            } else {
                return ResultUtils.getResult(ResultInfo.UPLOAD_TYPE_ERROR);
            }
            List<ProProjectGlobal> proProjectGlobals = new ArrayList<>();
            List<Map<String, String>> resultMap = new ArrayList<>();
            Map<String, String> result = null;
            ProProjectGlobal proProjectGlobal = null;
            // 获取工作表的第一个Sheet
            Sheet hssfSheet = wb.getSheetAt(0);
            if (hssfSheet != null) {
                int index = -1;
                for (int rowNum = 0; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                    Row hssfRow = hssfSheet.getRow(rowNum);
                    if (hssfRow != null) {
                        if (ExcelUtils.getValue(hssfRow.getCell(0)).contains("环境") &&
                                ExcelUtils.getValue(hssfRow.getCell(1)).contains("项目全局请求参数") &&
                                ExcelUtils.getValue(hssfRow.getCell(2)).contains("") &&
                                ExcelUtils.getValue(hssfRow.getCell(3)).contains("项目全局状态")) {
                            index = ++rowNum;
                            break;
                        }
                    }
                }

                if (index == -1) {
                    result = new HashMap<>();
                    result.put("reason", "excel模板不正确");
                    result.put("status", "1");
                    resultMap.add(result);
                    Map<String, Object> map = new HashMap<>();
                    map.put("resultMap", resultMap);
                    return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
                }

                // 循环行Row
                for (int rowNum = index; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                    Row hssfRow = hssfSheet.getRow(rowNum);
                    if (hssfRow != null) {
                        if (StringUtils.isBlank(ExcelUtils.getValue(hssfRow.getCell(0))) &&
                                StringUtils.isBlank(ExcelUtils.getValue(hssfRow.getCell(1))) &&
                                StringUtils.isBlank(ExcelUtils.getValue(hssfRow.getCell(2))) &&
                                StringUtils.isBlank(ExcelUtils.getValue(hssfRow.getCell(3)))) {
                            continue;
                        }
                        proProjectGlobal = new ProProjectGlobal();
                        String environment = ExcelUtils.getValue(hssfRow.getCell(0));//环境
                        if (StringUtils.isBlank(environment)) {
                            result = new HashMap<>();
                            result.put("reason", "环境不能为空！");
                            result.put("status", "1");
                            resultMap.add(result);
                            continue;
                        }
                        proProjectGlobal.setEnvironment(environment);
                        String http = ExcelUtils.getValue(hssfRow.getCell(1));//项目全局请求参数
                        if (StringUtils.isBlank(http)) {
                            result = new HashMap<>();
                            result.put("reason", "项目全局请求参数不能为空！");
                            result.put("status", "1");
                            resultMap.add(result);
                            continue;
                        }
                        proProjectGlobal.setHttp(http);
                        String projectId = ExcelUtils.getValue(hssfRow.getCell(2));//
                        if (StringUtils.isBlank(projectId)) {
                            result = new HashMap<>();
                            result.put("reason", "不能为空！");
                            result.put("status", "1");
                            resultMap.add(result);
                            continue;
                        }
                        proProjectGlobal.setProjectId(projectId);
                        String status = ExcelUtils.getValue(hssfRow.getCell(3));//项目全局状态
                        if (StringUtils.isBlank(status)) {
                            result = new HashMap<>();
                            result.put("reason", "项目全局状态不能为空！");
                            result.put("status", "1");
                            resultMap.add(result);
                            continue;
                        }
                        proProjectGlobal.setStatus(status);
                        proProjectGlobals.add(proProjectGlobal);
                    }
                }
                if (CommonUtils.isNotEmpty(proProjectGlobals)) {
                    resultMap.addAll(proProjectGlobalService.importProProjectGlobalExcel(proProjectGlobals));
                }
            }
            inputStream.close();
            Map<String, Object> map = new HashMap<>();
            map.put("resultMap", resultMap);
            return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.getResult(ResultInfo.ERROR);
        }
        return ResultUtils.getResult(ResultInfo.FAILED);
    }
}